/*******************************************************************************
 *
 * File Name:          ImportFieldAction.java
 *
 * Created:            2007-10-08 19:20:07
 *
 * Original Author:    yu.peng
 *
 *------------------------------------------------------------------------------
 * MODIFICATION HISTORY
 *------------------------------------------------------------------------------
 * WHEN                WHO                 WHY
 * 2007-10-08 19:20:07 yu.peng             new
 *------------------------------------------------------------------------------
 *
 ******************************************************************************/
/*******************/
/* PACKAGE SECTION */
/*******************/
package org.njo.webapp.root.action.dts;

import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.DiskFileUpload;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.ho.yaml.Yaml;
import org.njo.webapp.root.action.GenericAction;
import org.njo.webapp.root.model.activity.DTSActivity;

/**
 * TODO:comment
 *
 * @author yu.peng
 * @version 0.01
 */
public class ImportFieldAction extends GenericAction {

    // --------------------------------------------------------- Public Methods

    /**
     * Process the specified HTTP request, and create the corresponding HTTP
     * response (or forward to another web component that will create it).
     * Return an <code>ActionForward</code> instance describing where and how
     * control should be forwarded, or <code>null</code> if the response has
     * already been completed.
     *
     * @param mapping  The ActionMapping used to select this instance
     * @param form     The optional ActionForm bean for this request (if any)
     * @param request  The HTTP request we are processing
     * @param response The HTTP response we are creating
     * @throws Exception if the application business logic throws
     *                   an exception
     */
    public ActionForward execute(ActionMapping mapping,
                                 ActionForm form,
                                 HttpServletRequest request,
                                 HttpServletResponse response) throws Exception {

        // 判断是否是文件上传.
        String contentTypeHeader = request.getContentType();
        boolean isMultipart = (contentTypeHeader != null)
                && (contentTypeHeader.startsWith("multipart/form-data"));
        // 如果文件上传的情况下
        if (!isMultipart) {
            addMessage(request, new ActionMessage("dts.field.import.error.required"));
            return (new ActionForward("/importfield.tiles", false));
        } 

        // 分析请求并缓存上传内容.
        Map requestMap = parseMultiRequest(request);
        FileItem importFile = (FileItem)requestMap.get("importFile");
        InputStream inputStream = importFile.getInputStream();

        // 将文件内容转换成对象.
        List importList = (List)Yaml.load(inputStream);
        DTSActivity dtsactivity = new DTSActivity();

        dtsactivity.importField(importList);

        return (new ActionForward("/processor.listfield.tiles", false));
    }
    

    /**
     * 处理文件上传. <p/> 1,分析请求,返回请求参数Map. 2,将上传的文件会被放到缓存(临时文件)中.
     */
    private Map parseMultiRequest(HttpServletRequest request) {
        try {
            Map<String, Object> reqMap = new HashMap<String, Object>();
            DiskFileUpload fu = new DiskFileUpload();
            // 设置允许用户上传文件大小,单位:字节
            fu.setSizeMax(1024 * 1024 * 10);
            // 设置最多只允许在内存中存储的数据,单位:字节
            fu.setSizeThreshold(4096);
            // 设定编码集
            fu.setHeaderEncoding("utf-8");
            // 开始读取上传信息
            List fileItems = fu.parseRequest(request);
            for (int i = 0; i < fileItems.size(); i++) {
                FileItem item = (FileItem) fileItems.get(i);
                if (item.isFormField()) {
                    reqMap.put(item.getFieldName(), item.getString());
                } else {
                    reqMap.put(item.getFieldName(), item);
                }
            }
            return reqMap;
        } catch (FileUploadException e) {
            return null;
        }
    }
    
    

}